package com.lihan.GetSeatInLib.Service;

import java.util.Map.Entry;
import java.util.Random;
import java.util.stream.LongStream;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;

import com.lihan.GetSeatInLib.Domain.MailModel.MailTemplate;
import com.lihan.GetSeatInLib.Repository.MailRepository;
import com.lihan.GetSeatInLib.Tools.CommonFinal;

/**
 * 邮箱业务
 * @ClassName: MailService
 * @Description: 发送邮件服务
 * @author ASUS
 * @date 2022年1月14日
 *
 */
@Service
public class MailService {
	
	//Java邮件组件
	@Autowired
	private JavaMailSender MailSender;
	
	//thymeleaf的模板引擎，用于将邮件的thymeleaf模板渲染成html,然后发送
	@Autowired
	private TemplateEngine engine;
	
	//主要用来持久化发过的邮件
	@Autowired
	private MailRepository mailDao;
	
	private static Random random = new Random();
	
	
	//产生验证码的工具函数
	public static String ProductVerifyCode() {
		//产生一个五位数的验证码
		int VerifyCode = random.nextInt(90000)+10000;
		
		return String.valueOf(VerifyCode);
		
	}
	
	public boolean SendMail(MailTemplate template,String HTML) throws MessagingException {
		
		//创建邮件对象
		MimeMessage msg = MailSender.createMimeMessage();
		
		MimeMessageHelper helper = new MimeMessageHelper(msg,true);	
		
		//设置邮件的标题
		helper.setSubject(template.getTitle());
		
		//设置邮件发送日期
		helper.setSentDate(template.getSendDate());
		
		//设置邮件发送来源
		helper.setFrom(template.getFrom());
		
		//设置邮件发送目标邮箱
		helper.setTo(template.getTo());
		
		//设置邮件模板,
		//先设置邮件模板要使用的变量
		Context context = new Context();
		
		for(Entry<String, String> keyvaluePair : template.getContext().entrySet())
			context.setVariable(keyvaluePair.getKey(), keyvaluePair.getValue());
			
		
		helper.setText(engine.process(HTML, context),true);
		try {
			//先保存到数据库再发送邮件
			mailDao.save(template);
			
			MailSender.send(msg);
			return true;
		} catch (Exception e) {
			
		}
		return false;
	}


}
